package com.shishuo.cms.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.dao.AdminDao;
import com.shishuo.cms.dao.ConfigDao;
import com.shishuo.cms.entity.Config;

@Service
public class ConfigService extends BaseService<Config,String>
{
	private ConfigDao configDao;
	@Autowired
    public void setAdminDao(ConfigDao configDao) {  
		super.setBaseDao(configDao);
		this.configDao=configDao;
    }
	
	@CacheEvict(value = "config", key = "#key")
	public int deleteConfigByKey(String key) throws Exception {
		return this.deleteById(key);
	}
	@Cacheable(value = "config", key = "#key")
	public String getConfigByKey(String key){
		try
		{
			Config config = this.getById(key);
			if (config == null) {
				return "";
			} else {
				return config.getCmsValue();
			}
		}
		catch (Exception e)
		{
			logger.error("config key error!");
			return "";
		}
	}
	public Config addConfig(String key, String value) throws Exception {
		Config config = new Config();
		config.setCmsKey(key);
		config.setCmsValue(value);
		config.setCreateTime(new Date());
		this.insert(config);
		return config;
	}

	/**
	 * 更新所有的配置到数据库及其内存中
	 * @param allConfigs
	 * @throws Exception 
	 */
	@Transactional
	@CacheEvict(value = "config", allEntries = true)
	public void updateAll(List<Config> allConfigs) throws Exception
	{
		List<Config> allConfigsDb=this.getAllList();
		for (int i = 0; i < allConfigs.size(); i++)
		{
			boolean isFind=false;
			for (int j = 0; j < allConfigsDb.size(); j++)
			{
				if (allConfigsDb.get(j).getCmsKey().equals(allConfigs.get(i).getCmsKey()))
				{
					allConfigsDb.get(j).setCmsValue(allConfigs.get(i).getCmsValue());
					this.update(allConfigsDb.get(j));
					isFind=true;
				}
			}
			if (!isFind)
			{
				configDao.add(allConfigs.get(i));
			}
		}
	}
	
	/*public String getConfigByKey(String key) {
		if (key.equals("SYS_THEME"))
		{
			return "cms";
		}
		if (key.equals("SYS_SITEDESC"))
		{
			return "cms desc";
		}
		if (key.equals("SYS_SITENAME"))
		{
			return "cms name";
		}
		if (key.equals("IS_CACHE_HTML"))
		{
			return "1";
		}
		return "xxxxx";
	}*/

}
